package gx.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;

import gx.entity.Warehouse;
import gx.service.WarehouseService;

@Controller
@RequestMapping("/mng/ware")
public class WarehouseController {
	@Autowired
	private WarehouseService warehouseService;

	// 根据ID修改
	@RequestMapping("/list.jhtml")
	public ModelAndView list() throws Exception {
		ModelAndView mav = new ModelAndView("/mng/ware/list");
		List<Warehouse> list = warehouseService.findAll();
		mav.addObject("list", list);
		return mav;
	}

	// 新增
	@RequestMapping("/add.jhtml")
	public String add(Warehouse warehouse) {
		warehouseService.save(warehouse);
		return "redirect:/mng/ware/list.jhtml";
	}

	// 根据ID查询详情
	@RequestMapping("/detail.jhtml")
	public ModelAndView detail(Integer id) throws Exception {
		ModelAndView mav = new ModelAndView("/mng/ware/detail");
		Warehouse warehouse = warehouseService.get(id);
		mav.addObject("ware", warehouse);
		return mav;
	}

	// 根据ID修改
	@RequestMapping("/edit.jhtml")
	public String edit(Integer id, String lname, String address) {
		Warehouse w = warehouseService.get(id);
		w.setlname(lname);
		w.setAddress(address);
		warehouseService.update(w);
		return "redirect:/mng/ware/list.jhtml";
	}

	
	

	// 删除
//	@RequestMapping("/delete.jhtml")
//	public String delete(Integer id) {
//		warehouseService.delete(id);
//		System.out.println(id + "--------------------");
//		return "redirect:/mng/ware/list.jhtml";
//	}

	// 模糊查询
	@RequestMapping("/search.jhtml")
	public ModelAndView Search(String condition) throws Exception {
		ModelAndView mav = new ModelAndView("mng/ware/list");// ?
		List<Warehouse> list = warehouseService.findByName(condition);
		mav.addObject("list", list);
		return mav;
	}
	//ajax查询
	@RequestMapping(value = "/ajaxdelete.jhtml", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String ajaxList(Integer id) throws Exception {
		String rs = "";
		try {
			warehouseService.delete(id);
			rs = "删除成功！";
		} catch (Exception e) {
			//todo
			rs = "该管理已制单，无法删除！";
		}
		// 使用Jackson包来处理json
		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(rs);
		return json;
	}

}
